using System;
using System.Linq;
using UnityEngine;
using QFramework;
using Random = UnityEngine.Random;

namespace ProjectSurvival
{
    public partial class SimpleKnife : ViewController
    {
        private float intervalTime = 0f;
        private float knifeSpeed = 10;
        
        private void Update()
        {
            intervalTime += Time.deltaTime;
            if (intervalTime > Global.SimpleKnifeDuration.Value)
            {
                //解锁超级武器增加伤害
                var damageTime = Global.SuperKnife.Value ? Random.Range(2, 3) + 1 : 1;
                intervalTime = 0;
                if (Player.Instance)
                {
                    var enemies = FindObjectsByType<Enemy>(FindObjectsInactive.Exclude, FindObjectsSortMode.None)
                        .OrderBy(enemy => Player.Instance.Distance2D(enemy))
                        .Take(Global.SimpleKnifeCount.Value+Global.AdditionalFlyThingCount.Value);
                    int enemyCount = 0;
                    foreach (var enemy in enemies)
                    {
                        if (enemyCount < 4)
                        {
                            ActionKit.DelayFrame(10 * enemyCount, () => { AudioKit.PlaySound("Knife"); }).StartGlobal();
                            enemyCount++;
                        }

                        enemyCount++;
                        Knife.InstantiateWithParent(transform)
                            .Position(Player.Instance.transform.position)
                            .Show()
                            .Self(self =>
                            {
                                var rigidbody2d = self.GetComponent<Rigidbody2D>();
                                var knifeDirection = (enemy.transform.position - Player.Instance.transform.position)
                                    .normalized;
                                rigidbody2d.velocity = knifeDirection * knifeSpeed;
                                float angle = Vector2.SignedAngle(Vector2.up, knifeDirection);
                                var selfCatch = self;
                                selfCatch.transform.rotation = Quaternion.AngleAxis(angle, Vector3.forward);
                                int knifeAttackCount = 0;
                                selfCatch.OnTriggerEnter2DEvent(other =>
                                {
                                    var targetEnemy = GetEnemy(other.gameObject);
                                    if (targetEnemy)
                                    {
                                        //targetEnemy.Hurt(Global.SimpleKnifeDamage.Value);
                                        DamageSystem.CalculateDamage(Global.SimpleKnifeDamage.Value*damageTime,targetEnemy);
                                        knifeAttackCount++;
                                        if (knifeAttackCount >= Global.SimpleKnifeAttackCount.Value)
                                        {
                                            selfCatch.gameObject.DestroySelfGracefully();
                                        }
                                    }
                                }).UnRegisterWhenGameObjectDestroyed(selfCatch.gameObject);
                                ActionKit.OnUpdate.Register(() =>
                                {
                                    //小刀距离过远时销毁
                                    if (Player.Instance)
                                    {
                                        var distance = (Player.Instance.transform.position -
                                                        selfCatch.transform.position)
                                            .magnitude;
                                        if (distance > 20)
                                        {
                                            selfCatch.DestroyGameObjGracefully();
                                        }
                                    }
                                }).UnRegisterWhenGameObjectDestroyed(selfCatch);
                            });
                    }
                }
            }
        }

        private static Enemy GetEnemy(GameObject gameObject)
        {
            var hurtBox = gameObject.GetComponent<HitHurtBox>();
            if (hurtBox)
            {
                if (hurtBox.Owner.CompareTag("Enemy"))
                {
                    return hurtBox.Owner.GetComponent<Enemy>();
                }
            }

            return null;
        }
    }
}